/**
 * CoffeeMilk (C) 2010 Amen Hamdan
 * 
 * See the NOTICE file distributed with this work for additional 
 * information regarding copyright ownership.  This file is licenses
 * to you under the Apache License, Version 2.0 (the "License"); you 
 * may not use this file except in compliance with the License.  You 
 * may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 
 * implied. See the License for the specific language governing 
 * permissions and limitations under the License.    
 * 
 */
package ameen.rtm.coffeemilk.persistency;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class PersistencyManager {
	private static final String FILE_NAME = ".coffeemilk_settings.xml";
	
	public static synchronized void writeSettings(SettingsStore settingsStore) {
		try {
			String fileSeperator = System.getProperty("file.separator");
			String usrHome = System.getProperty("user.home") + fileSeperator;
			XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(usrHome + FILE_NAME))); 
			encoder.writeObject(settingsStore); 
			encoder.close(); 
			
		} catch (Exception e) { 
			e.printStackTrace();
		} 		
	}
	
	public static synchronized SettingsStore readSettings() {
		try {
			String fileSeperator = System.getProperty("file.separator");
			String usrHome = System.getProperty("user.home") + fileSeperator;
			XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(usrHome + FILE_NAME)));
			
			Object retVal = decoder.readObject();
			decoder.close();
			return (SettingsStore) retVal;
			
		} catch (Exception fnfe) {
			return new SettingsStore();
		}
	}
}
